(function() {
    var policyText = {
        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };
    var accessid = 'LTAI8ACJhIgN94KH';
    var accesskey = 'tHFkDUeGBoAA63mnWPwcsrgHhzHVAW';
    var host = "shuren-exam.oss-cn-beijing.aliyuncs.com";

    var bucket = "shuren-exam";


    (function() {

        // Private array of chars to use
        var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

        Math.uuid = function(len, radix) {
            var chars = CHARS,
                uuid = [],
                i;
            radix = radix || chars.length;

            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                // rfc4122, version 4 form
                var r;

                // rfc4122 requires these characters
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';

                // Fill in random data.  At i==19 set the high bits of clock sequence as
                // per rfc4122, sec. 4.1.5
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }

            return uuid.join('');
        };

        // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
        // by minimizing calls to random()
        Math.uuidFast = function() {
            var chars = CHARS,
                uuid = new Array(36),
                rnd = 0,
                r;
            for (var i = 0; i < 36; i++) {
                if (i == 8 || i == 13 || i == 18 || i == 23) {
                    uuid[i] = '-';
                } else if (i == 14) {
                    uuid[i] = '4';
                } else {
                    if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                    r = rnd & 0xf;
                    rnd = rnd >> 4;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
            return uuid.join('');
        };

        // A more compact, but less performant, RFC4122v4 solution:
        Math.uuidCompact = function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        };
    })();



    // 封装console.log
    function printLog(title, info) {
        window.console && console.log(title, info);
    }
    // ------- 配置上传的初始化事件 -------
    function uploadInit() {
        var uuid = Math.uuid();
        var policyBase64 = Base64.encode(JSON.stringify(policyText)),
            message = policyBase64;
        var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {
            asBytes: true
        });
        var signature = Crypto.util.bytesToBase64(bytes);

        // this 即 editor 对象
        var editor = this;
        // 编辑器中，触发选择图片的按钮的id
        var btnId = editor.customUploadBtnId;
        // 编辑器中，触发选择图片的按钮的父元素的id
        var containerId = editor.customUploadContainerId;

        //实例化一个上传对象
        var uploader = new plupload.Uploader({
            //container:containerId,
            browse_button: btnId, // 选择文件的按钮的id
            url: host, // 服务器端的上传地址
            runtimes: 'html5,flash,silverlight,html4',
            flash_swf_url: '${path}/static/imageUpload/lib/plupload-2.1.2/js/Moxie.swf',
            silverlight_xap_url: '${path}/static/imageUpload/lib/plupload-2.1.2/js/Moxie.xap',
            filters: {
                mime_types: [
                    //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
                    {
                        title: "图片文件",
                        extensions: "jpeg,jpg,gif,png,bmp"
                    }
                ]
            },
            multipart_params: {
                'Filename': uuid,
                'key': uuid,
                'policy': policyBase64,
                'OSSAccessKeyId': accessid,
                'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                'signature': signature,
            }
        });

        //存储所有图片的url地址
        var urls = [];

        //初始化
        uploader.init();

        //绑定文件添加到队列的事件
        uploader.bind('FilesAdded', function(uploader, files) {
            //显示添加进来的文件名
            $.each(files, function(key, value) {
                printLog('添加文件' + value.name);
            });

            // 文件添加之后，开始执行上传
            uploader.start();
        });

        //单个文件上传之后
        uploader.bind('FileUploaded', function(uploader, file, responseObject) {
            var url;
            if (responseObject.status >= 200 || responseObject.status < 200) {
                url = '$' + uuid + ':' + bucket;
                urls.push(url);
                //先将url地址存储来，待所有图片都上传完了，再统一处理
            } else {
                url = responseObject.response;
                // 插入到编辑器中
                editor.command(null, 'insertHtml', '<img src="' + value + '" style="max-width:100%;"/>');
            }
            printLog('一个图片上传完成，返回的url是' + url);
        });

        //全部文件上传时候
        uploader.bind('UploadComplete', function(uploader, files) {
            printLog('所有图片上传完成');

            // 用 try catch 兼容IE低版本的异常情况
            try {
                //打印出所有图片的url地址
                $.each(urls, function(key, value) {
                    printLog('即将插入图片' + value);
                    $.ajax({
                        url: "/ueditor/getPicUrl?param=" + value,
                        type: 'get',
                        dataType: 'text'
                    }).done(function(imgUrl) {
                        // 插入到编辑器中
                        editor.command(null, 'insertHtml', '<img src="' + imgUrl + '" style="max-width:100%;"/>');
                    }).fail(function() {
                        console.log(arguments);
                    });
                });
            } catch (ex) {
                // 此处可不写代码
            } finally {
                //清空url数组
                urls = [];

                // 隐藏进度条
                editor.hideUploadProgress();
                uploader.destroy();
                uploadInit.call(editor);
            }
        });

        // 上传进度条
        uploader.bind('UploadProgress', function(uploader, file) {
            // 显示进度条
            editor.showUploadProgress(file.percent);
        });
    }
    var editor = new wangEditor('editor-trigger');
    // 自定义菜单
    editor.config.menus = [
        'source',
        '|',
        'bold',
        'underline',
        'italic',
        'strikethrough',
        //'eraser',
        'forecolor',
        'bgcolor',
        '|',
        //'quote',
        'fontfamily',
        'fontsize',
        'lineheight',
        'indent',
        'head',
        'unorderlist',
        'orderlist',
        'alignleft',
        'aligncenter',
        'alignright',
        '|',
        'link',
        'unlink',
        'table',
        //'emotion',
        //'|',
        'img',
        //'video',
        //'location',
        //'insertcode',
        '|',
        'undo',
        'redo',
        'fullscreen'
    ];

    // 只粘贴纯文本
    editor.config.pasteText = true;
    // onchange 事件
    editor.onchange = function() {
        //console.log(this.$txt.html());
    };
    editor.config.customUpload = true; // 配置自定义上传的开关
    editor.config.customUploadInit = uploadInit; // 配置上传事件，uploadInit方法已经在上面定义了
    editor.create();

    //表单提交处理
    $('#doSave').on('click', function() {
        editor.$txt.html(_getContent());
    });
    $('#previewBtn').on('click', function() {
        var w = window.open('', '_blank', ''),
            d = w.document;
        d.open();
        d.write('<div style="margin:0 auto;width:600px"><style>img{display:block;max-width:100%;margin:0 auto;}</style>' + _getContent() + '</div>');
        d.close();
    });

    function _getContent() {
        var content = editor.$txt.html();
        content = content.replace(/(<img.*?>)<br><\/p>/gi, '$1</p>').replace(/(<p><br><\/p>)+$/gi, '').replace(/(<br\/?>)+$/i, '');
        return content;
    }
})();